"""
下单账号管理页面
"""
from PyQt6.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QTableWidget,
                           QTableWidgetItem, QPushButton, QLineEdit, QLabel,
                           QHeaderView, QFrame, QDialog, QMessageBox, QFileDialog)
from PyQt6.QtCore import Qt
from PyQt6.QtGui import QFont, QColor
from com.db.order_account_manager import OrderAccountManager
from com.db.models import OrderAccount
from gui.styles.table_style import apply_default_table_style, set_columns_stretch
from gui.styles.pagination_style import PaginationWidget
from .login_dialog import LoginDialog
from biz.account_checker import AccountChecker, AccountType
import logging
import json
from datetime import datetime

# 配置日志
logger = logging.getLogger(__name__)

class AccountPage(QWidget):
    """下单账号管理页面"""
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.account_manager = OrderAccountManager()
        self.account_checker = AccountChecker()
        self.setup_ui()
        self.load_accounts()  # 从数据库加载账号数据
        self.setup_connections()  # 设置信号连接
    
    def setup_ui(self):
        """初始化UI"""
        layout = QVBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)  # 移除边距，使表格占满整个空间
        layout.setSpacing(0)  # 减少间距
        
        # 工具栏区域
        toolbar_frame = QFrame()
        toolbar_frame.setStyleSheet("""
            QFrame {
                background-color: white;
                border: none;
                border-bottom: 1px solid #ebeef5;
            }
        """)
        toolbar_layout = QHBoxLayout(toolbar_frame)
        toolbar_layout.setContentsMargins(15, 10, 15, 10)
        
        # 右侧按钮区域
        right_widget = QWidget()
        right_layout = QHBoxLayout(right_widget)
        right_layout.setContentsMargins(0, 0, 0, 0)
        right_layout.setSpacing(10)
        
        # 刷新按钮
        refresh_btn = QPushButton("刷新")
        refresh_btn.setObjectName("refreshBtn")
        refresh_btn.setStyleSheet("""
            QPushButton#refreshBtn {
                padding: 5px 15px;
                background-color: #67c23a;
                color: white;
                border: none;
                border-radius: 2px;
                font-size: 12px;
                min-width: 60px;
            }
            QPushButton#refreshBtn:hover {
                background-color: #85ce61;
            }
        """)
        refresh_btn.clicked.connect(self.refresh_accounts)
        right_layout.addWidget(refresh_btn)
        
        # 导入账号按钮
        import_btn = QPushButton("导入账号")
        import_btn.setObjectName("importBtn")
        import_btn.setStyleSheet("""
            QPushButton#importBtn {
                padding: 5px 15px;
                background-color: white;
                color: #606266;
                border: 1px solid #dcdfe6;
                border-radius: 2px;
                font-size: 12px;
                min-width: 60px;
            }
            QPushButton#importBtn:hover {
                color: #409eff;
                border-color: #c6e2ff;
                background-color: #ecf5ff;
            }
        """)
        
        right_layout.addWidget(import_btn)
        
        # 添加账号按钮
        add_btn = QPushButton("添加/更新账号")
        add_btn.setObjectName("addBtn")
        add_btn.setStyleSheet("""
            QPushButton#addBtn {
                padding: 5px 15px;
                background-color: #409eff;
                color: white;
                border: none;
                border-radius: 2px;
                font-size: 12px;
                min-width: 60px;
            }
            QPushButton#addBtn:hover {
                background-color: #66b1ff;
            }
        """)
        
        right_layout.addWidget(add_btn)
        
        toolbar_layout.addStretch()  # 添加弹性空间，将按钮推到右侧
        toolbar_layout.addWidget(right_widget)
        
        # 添加工具栏到主布局
        layout.addWidget(toolbar_frame)
        
        # 表格
        self.table = QTableWidget()
        apply_default_table_style(self.table)
        
        # 设置表格列
        headers = ["id", "uu用户id", "名称", "uutoken", "设备id", "uk", "创建时间", "更新时间", "状态", "操作"]
        self.table.setColumnCount(len(headers))
        self.table.setHorizontalHeaderLabels(headers)
        
        # 设置表格列宽
        set_columns_stretch(self.table)
        
        # 分页控件
        self.pagination = PaginationWidget()
        self.pagination.prev_btn.clicked.connect(self.on_prev_page)
        self.pagination.next_btn.clicked.connect(self.on_next_page)
        self.pagination.page_size_spin.valueChanged.connect(self.on_page_size_changed)
        
        # 添加到主布局
        layout.addWidget(self.table)
        layout.addWidget(self.pagination)
    
    def load_accounts(self, keyword=None):
        """从数据库加载账号数据"""
        # 计算总数
        total_count = len(self.account_manager.get_accounts(keyword))
        
        # 获取当前页数据
        page = self.pagination.page
        page_size = self.pagination.page_size
        offset = (page - 1) * page_size
        
        # 获取分页数据
        accounts = self.account_manager.get_accounts(keyword, limit=page_size, offset=offset)
        
        # 更新分页状态
        self.pagination.update_state(page, total_count)
        
        # 更新表格
        self.update_table(accounts)
            
    def delete_account(self, row):
        """删除账号
        
        Args:
            row: 表格行号
        """
        # 获取账号ID
        account_id = int(self.table.item(row, 0).text())
        account_name = self.table.item(row, 2).text()
        
        # 确认删除
        reply = QMessageBox.question(
            self,
            "确认删除",
            f"确定要删除账号 {account_name} 吗？",
            QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
            QMessageBox.StandardButton.No
        )
        
        if reply == QMessageBox.StandardButton.Yes:
            # 执行删除
            if self.account_manager.delete_account(account_id):
                QMessageBox.information(self, "提示", "删除成功")
                # 重新加载数据
                self.load_accounts()
            else:
                QMessageBox.warning(self, "错误", "删除失败")
    
    def setup_connections(self):
        """设置信号连接"""
        # 找到添加按钮并连接点击事件
        add_btn = self.findChild(QPushButton, "addBtn")
        if add_btn:
            add_btn.clicked.connect(self.show_add_dialog)
            
        # 找到导入按钮并连接点击事件
        import_btn = self.findChild(QPushButton, "importBtn")
        if import_btn:
            import_btn.clicked.connect(self.import_accounts)
            
        # 找到刷新按钮并连接点击事件
        refresh_btn = self.findChild(QPushButton, "refreshBtn")
        if refresh_btn:
            refresh_btn.clicked.connect(self.refresh_accounts)
    
    def show_add_dialog(self):
        """显示添加账号对话框"""
        from .add_account_dialog import AddAccountDialog
        dialog = AddAccountDialog(self)
        dialog.account_added.connect(self.refresh_accounts)  # 连接信号，当账号添加成功时刷新列表
        dialog.exec()  # 执行对话框
    
    def on_prev_page(self):
        """上一页"""
        if self.pagination.page > 1:
            self.pagination.page -= 1
            self.load_accounts()
    
    def on_next_page(self):
        """下一页"""
        total_pages = (self.pagination.total_count + self.pagination.page_size - 1) // self.pagination.page_size
        if self.pagination.page < total_pages:
            self.pagination.page += 1
            self.load_accounts()
    
    def on_page_size_changed(self, value):
        """页面大小改变"""
        self.pagination.page_size = value
        self.pagination.page = 1  # 重置到第一页
        self.load_accounts()
    
    def check_account(self, row):
        """检测账号
        
        Args:
            row: 表格行号
        """
        try:
            # 获取账号ID
            account_id = int(self.table.item(row, 0).text())
            
            # 执行检测
            success, message, _ = self.account_checker.check_account(
                account_id=account_id,
                account_type=AccountType.ORDER  # 这里是下单账号页面
            )
            
            # 刷新账号列表，获取最新状态
            self.load_accounts()
            
            # 显示提示信息
            if success:
                QMessageBox.information(self, "检测结果", message)
            else:
                QMessageBox.warning(self, "检测结果", message)
                
        except Exception as e:
            logger.error(f"检测账号时发生错误: {str(e)}")
            QMessageBox.warning(self, "错误", f"检测账号时发生错误: {str(e)}")

    def format_timestamp(self, timestamp):
        """将时间戳转换为年-月-日 时:分:秒格式
        
        Args:
            timestamp: 时间戳（毫秒）
            
        Returns:
            str: 格式化后的时间字符串
        """
        if not timestamp:
            return ""
        
        # 转换为秒
        try:
            # 确保timestamp是整数
            timestamp = int(timestamp)
            # 如果是毫秒时间戳，转换为秒
            if timestamp > 9999999999:
                timestamp = timestamp / 1000
            
            # 转换为datetime对象并格式化
            dt = datetime.fromtimestamp(timestamp)
            return dt.strftime("%Y-%m-%d %H:%M:%S")
        except Exception as e:
            logger.error(f"时间戳转换失败: {e}")
            return str(timestamp)
            
    def update_table(self, accounts):
        """更新表格数据
        
        Args:
            accounts: 账号数据列表
        """
        # 更新表格
        self.table.setRowCount(len(accounts))
        
        for row, account in enumerate(accounts):
            # ID
            id_item = QTableWidgetItem(str(account["id"]))
            id_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
            self.table.setItem(row, 0, id_item)
            
            # uu用户id
            uu_user_id_item = QTableWidgetItem(str(account["uu_user_id"]))
            uu_user_id_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
            self.table.setItem(row, 1, uu_user_id_item)
            
            # 名称
            name_item = QTableWidgetItem(account["name"])
            name_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
            self.table.setItem(row, 2, name_item)
            
            # uutoken
            token_item = QTableWidgetItem(account["uu_token"])
            token_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
            self.table.setItem(row, 3, token_item)
            
            # 设备id
            device_id_item = QTableWidgetItem(account["device_id"])
            device_id_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
            self.table.setItem(row, 4, device_id_item)
            
            # uk
            uk_item = QTableWidgetItem(account["uk"])
            uk_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
            self.table.setItem(row, 5, uk_item)
            
            # 创建时间
            create_at_str = self.format_timestamp(account["create_at"])
            create_at_item = QTableWidgetItem(create_at_str)
            create_at_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
            self.table.setItem(row, 6, create_at_item)
            
            # 更新时间
            update_at_str = self.format_timestamp(account["update_at"])
            update_at_item = QTableWidgetItem(update_at_str)
            update_at_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
            self.table.setItem(row, 7, update_at_item)
            
            # 状态
            status_item = QTableWidgetItem(account["status"])
            status_item.setForeground(QColor("#67c23a" if account["status"] == "正常" else "#f56c6c"))
            status_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
            self.table.setItem(row, 8, status_item)
            
            # 操作按钮
            action_widget = QWidget()
            action_layout = QHBoxLayout(action_widget)
            action_layout.setContentsMargins(4, 4, 4, 4)
            action_layout.setSpacing(8)
            
            button_styles = {
                "删除": ("#f56c6c", "#fef0f0"),
                "检测": ("#409eff", "#ecf5ff"),
                "启用": ("#67c23a", "#f0f9eb"),
                "停用": ("#e6a23c", "#fdf6ec")
            }
            
            # 添加启用/停用按钮
            status_btn_text = "停用" if account["status"] == "正常" else "启用"
            status_btn = QPushButton(status_btn_text)
            status_btn.setFixedSize(45, 25)
            color, bg_color = button_styles[status_btn_text]
            status_btn.setStyleSheet(f"""
                QPushButton {{
                    padding: 0px;
                    background-color: {bg_color};
                    border: none;
                    border-radius: 2px;
                    font-size: 12px;
                    color: {color};
                }}
                QPushButton:hover {{
                    background-color: {color};
                    color: white;
                }}
            """)
            status_btn.clicked.connect(lambda checked, a=account: self.toggle_account_status(a))
            action_layout.addWidget(status_btn)
            
            for action in ["删除", "检测"]:
                btn = QPushButton(action)
                btn.setFixedSize(45, 25)
                color, bg_color = button_styles[action]
                btn.setStyleSheet(f"""
                    QPushButton {{
                        padding: 0px;
                        background-color: {bg_color};
                        border: none;
                        border-radius: 2px;
                        font-size: 12px;
                        color: {color};
                    }}
                    QPushButton:hover {{
                        background-color: {color};
                        color: white;
                    }}
                """)
                # 为删除按钮添加点击事件
                if action == "删除":
                    btn.clicked.connect(lambda checked, row=row: self.delete_account(row))
                # 为检测按钮添加点击事件
                elif action == "检测":
                    btn.clicked.connect(lambda checked, row=row: self.check_account(row))
                action_layout.addWidget(btn)
            
            action_layout.addStretch()
            self.table.setCellWidget(row, 9, action_widget)
            
            # 设置行高
            self.table.setRowHeight(row, 45)
            
    def add_account_to_table(self, account):
        """添加账号到表格
        
        Args:
            account: 账号数据（字典格式）
        """
        row = self.table.rowCount()
        self.table.insertRow(row)
        
        # 设置每列的数据
        self.table.setItem(row, 0, QTableWidgetItem(str(account.get('id', ''))))
        self.table.setItem(row, 1, QTableWidgetItem(account.get('uu_user_id', '')))
        self.table.setItem(row, 2, QTableWidgetItem(account.get('name', '')))
        self.table.setItem(row, 3, QTableWidgetItem(account.get('uu_token', '')))
        self.table.setItem(row, 4, QTableWidgetItem(account.get('device_id', '')))
        self.table.setItem(row, 5, QTableWidgetItem(account.get('uk', '')))
        self.table.setItem(row, 6, QTableWidgetItem(self.format_timestamp(account.get('create_at', ''))))
        self.table.setItem(row, 7, QTableWidgetItem(self.format_timestamp(str(account.get('update_at', '')))))
        self.table.setItem(row, 8, QTableWidgetItem(account.get('status', '')))
        
        # 添加操作按钮
        operation_widget = QWidget()
        operation_layout = QHBoxLayout()
        operation_layout.setContentsMargins(5, 2, 5, 2)
        operation_layout.setSpacing(5)
        
        # 删除按钮
        delete_btn = QPushButton("删除")
        delete_btn.setFixedWidth(60)
        delete_btn.clicked.connect(lambda: self.delete_account(account.get('id')))
        operation_layout.addWidget(delete_btn)
        
        operation_widget.setLayout(operation_layout)
        self.table.setCellWidget(row, 9, operation_widget)

    def refresh_accounts(self):
        """刷新账号列表"""
        try:
            self.load_accounts()
            logger.info("账号列表刷新成功")
        except Exception as e:
            logger.error(f"刷新账号列表失败: {str(e)}")
            QMessageBox.warning(self, "提示", "刷新账号列表失败")

    def import_accounts(self):
        """导入账号"""
        # 打开文件选择对话框
        file_path, _ = QFileDialog.getOpenFileName(
            self,
            "选择账号数据文件",
            "",
            "JSON Files (*.json);;All Files (*)"
        )
        
        if not file_path:
            return
            
        try:
            # 读取JSON文件
            with open(file_path, 'r', encoding='utf-8') as f:
                accounts = json.load(f)
                
            if not isinstance(accounts, list):
                QMessageBox.warning(self, "错误", "无效的账号数据格式")
                return
                
            success_count = 0
            update_count = 0
            error_count = 0
            
            # 导入每个账号
            for account in accounts:
                try:
                    # 检查必要字段
                    required_fields = ['name', 'uu_token', 'device_id', 'uu_user_id']
                    if not all(field in account for field in required_fields):
                        error_count += 1
                        continue
                        
                    # 设置时间戳
                    account['create_at'] = account.get('create_at', datetime.utcnow().isoformat())
                    account['update_at'] = int(datetime.now().timestamp() * 1000)
                    
                    # 处理pay_methods字段，将列表转换为JSON字符串
                    if 'pay_methods' in account and isinstance(account['pay_methods'], list):
                        account['pay_methods'] = json.dumps(account['pay_methods'])
                    
                    # 检查是否存在相同uu_user_id的账号
                    session, query = self.account_manager.db.query_with_session(OrderAccount)
                    try:
                        uu_user_id = account.get('uu_user_id')
                        existing_account = query.filter(OrderAccount.uu_user_id == uu_user_id).first()
                        is_update = existing_account is not None
                    finally:
                        session.close()
                    
                    # 保存到数据库
                    if self.account_manager.add_account(account):
                        if is_update:
                            update_count += 1
                        else:
                            success_count += 1
                    else:
                        error_count += 1
                        
                except Exception as e:
                    logger.error(f"导入账号失败: {str(e)}")
                    error_count += 1
                    
            # 显示导入结果
            message = f"导入完成\n\n新增: {success_count}\n更新: {update_count}\n失败: {error_count}"
            QMessageBox.information(self, "导入结果", message)
            
            # 重新加载数据
            self.load_accounts()
            
        except Exception as e:
            QMessageBox.critical(self, "错误", f"导入失败: {str(e)}")

    def toggle_account_status(self, account):
        """切换账号状态（启用/停用）
        
        Args:
            account: 账号数据
        """
        account_id = account["id"]
        current_status = 1 if account["status"] == "正常" else 0
        new_status = 0 if current_status == 1 else 1
        status_text = "启用" if new_status == 1 else "停用"
        
        # 确认对话框
        reply = QMessageBox.question(
            self,
            "确认操作",
            f"确定要{status_text}账号 {account['name']} 吗？",
            QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
            QMessageBox.StandardButton.No
        )
        
        if reply == QMessageBox.StandardButton.Yes:
            # 更新账号状态
            success = self.account_manager.update_account_status(account_id, status=new_status)
            
            if success:
                QMessageBox.information(self, "操作成功", f"账号已{status_text}")
                # 刷新账号列表
                self.load_accounts()
            else:
                QMessageBox.warning(self, "操作失败", f"账号{status_text}失败")
